import babel from "@rollup/plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";

import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";

import serve from "rollup-plugin-serve";
import livereload from "rollup-plugin-livereload";

const common = {
  banner: "/* my-library version */",
  footer: "/* follow me on Twitter! */",
  globals: {
    lodash: "_", // 告诉 rollup 全局变量 _ 即是 lodash
    jquery: "$", // 告诉 rollup 全局变量 $ 即是 jquery
  },
};

export default {
  input: "src/main.ts",
  external: ["lodash", "jquery"],
  output: [
    {
      file: "dist/boundle.es.js",
      format: "es",
      ...common,
    },
    {
      file: "dist/boundle.cjs.js",
      format: "cjs", // amd es iife umd cjs
      exports: "named",
      ...common,
    },
    {
      file: "dist/boundle.iife.js",
      format: "iife",
      exports: "named",
      name: "ly",
      ...common,
    },
    {
      file: "dist/boundle.umd.js",
      format: "umd", // 支持范围广
      exports: "named",
      name: "ly",
      ...common,
    },
    {
      file: "dist/boundle.amd.js",
      format: "amd", // 现在不咋用了
      exports: "named",
      ...common,
    },
  ],
  plugins: [
    // babel 解析 ES6+ 的高级语法
    babel({
      // exclude: "node_modules/**",
      include: "src/**",
      babelHelpers: "bundled",
    }),
    resolve({
      mainFields: ["module", "jsnext:main", "main"], // 入口点
      extensions: [".mjs", ".js", ".json", ".node"], // 入口文件格式
    }), // 告诉 rollup 如何查找第三方模块
    commonjs(), // 支持导入 commonjs 规范的模块
    typescript(), // 解析 ts

    process.env.NODE_ENV !== "production" ? null : terser(), // 压缩 js
    postcss(), // 解析 css

    process.env.NODE_ENV !== "production"
      ? serve({
          open: true,
          openPage: "/public/index.html",
          port: 3000,
          contentBase: "",
        })
      : null,
    process.env.NODE_ENV !== "production"
      ? livereload(resolve(__dirname, "dist"))
      : null, // 热重载，并且监听 dist 目录
  ],
};
